import { resolve } from 'node:path';
import { is } from '@electron-toolkit/utils';
import { BrowserWindow } from 'electron';
import log from './logger';

export function loadWindowUrl(win: BrowserWindow, routePath?: string, name: string = 'index.html') {
  const isDev = is.dev && process.env['ELECTRON_RENDERER_URL'];
  if (isDev) {
    const devUrl = `${process.env['ELECTRON_RENDERER_URL']}/${name}`;
    const fullUrl = routePath ? `${devUrl}#${routePath}` : devUrl;
    return win.loadURL(fullUrl);
  } else {
    const filePath = resolve(__dirname, `../renderer/${name}`);
    win
      .loadFile(filePath)
      .then(() => {
        log.info('页面加载完成后设置路由:' + routePath);
        if (routePath) {
          // 页面加载完成后设置路由
          win.webContents.executeJavaScript(`
          window.location.hash = '${routePath}';
        `);
        }
      })
      .catch((err) => {
        log.error('加载文件失败:', err);
      });
  }
}
